package ink.yuanchu.picachoframework.security;

import ink.yuanchu.picachoframework.dao.RoleMapper;
import ink.yuanchu.picachoframework.dao.UserMapper;
import ink.yuanchu.picachoframework.entity.Role;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 *
 * @author ziyuan
 * @Date: 2021/02/20/12:34
 * @Description:
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RoleMapper roleMapper;

    /**
     * 封装用户信息
     * @param s
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        if (s == null || "".equals(s)) {
            throw new RuntimeException("用户不能为空");
        }
        //todo  如果用户不存在都要报异常的话，日志早就爆了
        // 调用方法查询用户
        ink.yuanchu.picachoframework.entity.User user = userMapper.findUserByUsername(s);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
//        for (Role role:userMapper.findRoleByUsername(s)) {
//            authorities.add(new SimpleGrantedAuthority("ROLE_"+role.getRoleName()));
//        }
        Role role = roleMapper.findByRoleId(user.getRoleId());
        authorities.add(new SimpleGrantedAuthority("ROLE_"+role.getRoleName()));
        return new org.springframework.security.core.userdetails.User(user.getUsername(),"{noop}"+user.getPassword(),authorities);
    }
}
